package com.itheima.security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

//security数据库版认证和授权
@Component
public class HealthUserDetailServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据账号 查询当前用户密码,所有角色权限关键字
        //根据账号查询当用户角色权限信息
        UserVO userVO = userService.findUserDetailsByUsername(username);
        if (userVO == null) {
            //如果没有账号信息，账号认证失败
            return null;
        }
        //创建用户角色权限信息集合
        //GrantedAuthority的实现类SimpleGrantedAuthority
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        //获取该用户对应的角色
        List<RoleVO> roles = userVO.getRoles();
        for (RoleVO role : roles) {
            //将用户角色信息保存到集合中
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            //获取用户角色权限信息
            List<Permission> permissionList = role.getPermissionList();
            for (Permission permission : permissionList) {
                //将用户角色权限信息保存到集合中
                grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //UserDetails他的实现类是User
        //User需要用户账号，密码，用户角色权限信息集合
        return new User(username,userVO.getPassword(),grantedAuthorityList);
    }

}
